package com.guoxue.util;

import java.util.Random;

import com.alibaba.fastjson.JSONObject;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
/**
 * 短信发送工具类
 * @author young
 *
 */
public class MessageSendUtil {
	private static final String appkey = "23412109";
	private static final String secret = "d0ab8fab2341e93293979a442b84493f";	
	public static JSONObject sendMessage(String tel,String type){
		try {
			TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", appkey, secret);
			AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
			String radomInt = getRandNum(4);
			if (type.equals("reg")){
				req.setSmsType( "normal" );
				req.setSmsFreeSignName( "注册验证" );
				req.setSmsParamString(JsonUtil.jsonFomart(radomInt, "博约",OtherUtils.getCurrentDate().substring(11)).toJSONString());
				req.setRecNum(tel);
				req.setSmsTemplateCode( "SMS_12670216" );
			}else if(type.equals("modify")) {
				req.setSmsType( "normal" );
				req.setSmsFreeSignName( "变更验证" );
				req.setSmsParamString(JsonUtil.jsonFomart(radomInt, "博约账号",OtherUtils.getCurrentDate().substring(11)).toJSONString());
				req.setRecNum(tel);
				req.setSmsTemplateCode( "SMS_12620345" );
			}
			AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
			JSONObject obj = new JSONObject();
			obj.put("isSuccess", rsp.isSuccess()?"1":"2");
			obj.put("radomInt", radomInt);
			return obj;
		} catch (Exception e) {
			LoggerUtil.logInfo(e, "获取验证码出错");
			JSONObject obj = new JSONObject();
			obj.put("isSuccess", "2");
			obj.put("radomInt", 0);
			return obj;
		}

	}
	
	public static String getRandNum(int charCount) {
        String charValue = "";
        for (int i = 0; i < charCount; i++) {
            char c = (char) (randomInt(0, 10) + '0');
            charValue += String.valueOf(c);
        }
        return charValue;
    }
	public static int randomInt(int from, int to) {
        Random r = new Random();
        return from + r.nextInt(to - from);
    }
	
}
